package com.quyeying.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quyeying.entity.*;
import com.quyeying.mapper.TblProductDao;
import com.quyeying.service.*;
import com.quyeying.utils.AsyncTask;
import com.quyeying.utils.OssUtil;
import com.quyeying.utils.RedisUtil;
import com.quyeying.utils.result.R;
import com.quyeying.utils.result.ResultEnum;
import com.quyeying.utils.result.ReturnPageData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品表
 * </p>
 *
 * @author jll
 * @since 2022-07-19
 */
@Slf4j
@Service
public class TblProductServiceImpl extends ServiceImpl<TblProductDao, TblProductEntity> implements TblProductService {

    @Resource
    private TblProductImageService tblProductImageService;
    @Resource
    private TblProductDao tblProductDao;
    @Resource
    RedisUtil redisUtil;
    @Resource
    private OssUtil ossUtil;
    @Resource
    TblProductSkuService productSkuService;
    @Resource
    TblProductExtendService productExtendService;
    @Resource
    TblProductExtendImageService productExtendImageService;
    @Resource
    TblProductParamService productParamService;
    @Resource
    TblProductSkuService skuService;
    @Resource
    TblPopularizeVideoService popularizeVideoService;
    @Resource
    TblProductCategoryService tblProductCategoryService;
    @Value("${oss.imageCompress}")
    private String imageCompress;
    @Value("${oss.imageDetails}")
    private String imageDetails;
    @Resource
    private TblMerchantService tblMerchantService;
    @Resource
    private AsyncTask asyncTask;

    @Override
    public R findListByPage(Integer page, Integer pageCount, Integer productBuyZt, Long id) {
        IPage<TblProductEntity> wherePage = new Page<>(page, pageCount);
        TblProductEntity where = new TblProductEntity();
        where.setProductBuyZt(productBuyZt);
        if (tblMerchantService.getById(id).getType()==1){
            where.setMerchantId(id);
        }
        IPage<TblProductEntity> iPage = baseMapper.selectPage(wherePage, Wrappers.query(where).orderByDesc("id"));
        QueryWrapper<TblProductImageEntity> productImageEntityQueryWrapper = new QueryWrapper<>();
        QueryWrapper<TblProductSkuEntity> skuEntityQueryWrapper = new QueryWrapper<>();
        iPage.getRecords().forEach(item -> {
            //商品封面
            productImageEntityQueryWrapper.clear();
            productImageEntityQueryWrapper.eq("product_id", item.getId()).orderByAsc("sort").last("limit 1");
            item.setProductCover(tblProductImageService.getOne(productImageEntityQueryWrapper).getImageUrl()+imageCompress);
            //商品价格
            skuEntityQueryWrapper.clear();
            skuEntityQueryWrapper.eq("pid", item.getId()).orderByAsc("product_scribing_price");
            List<TblProductSkuEntity> skuEntityList = productSkuService.list(skuEntityQueryWrapper);
            if (skuEntityList.size()>0){
                item.setCrossedPrice(skuEntityList.get(0).getProductScribingPrice().toString());
                BigDecimal price = skuEntityList.stream().min(Comparator.comparing(TblProductSkuEntity::getPrice)).get().getPrice();
                item.setProductPrice(price.toString());
            }
        });
        return R.success(ReturnPageData.fillingData(iPage));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R add(TblProductEntity tblProductEntity) {
        //先插入商品信息，得到商品id
        baseMapper.insert(tblProductEntity);
        //设置商品图片
        tblProductEntity.getTblProductImageEntityList().forEach(item -> item.setProductId(tblProductEntity.getId()));
        tblProductImageService.saveBatch(tblProductEntity.getTblProductImageEntityList());
        //设置商品规格
        tblProductEntity.getProductSkuEntityList().forEach(item -> item.setPid(tblProductEntity.getId()));
        productSkuService.saveBatch(tblProductEntity.getProductSkuEntityList());
        //设置商品扩展介绍
        tblProductEntity.getProductIntroduceExtend().setPid(tblProductEntity.getId());
        productExtendService.add(tblProductEntity.getProductIntroduceExtend());
        //设置商品扩展介绍图片
        if (!ObjectUtils.isEmpty(tblProductEntity.getProductIntroduceExtendImages())) {
            tblProductEntity.getProductIntroduceExtendImages().forEach(item -> {
                item.setPid(tblProductEntity.getId());
            });
            productExtendImageService.saveBatch(tblProductEntity.getProductIntroduceExtendImages());
        }
        //设置商品参数
        if (!ObjectUtils.isEmpty(tblProductEntity.getProductParamEntityList())) {
            tblProductEntity.getProductParamEntityList().forEach(item -> {
                item.setPid(tblProductEntity.getId());
            });
            productParamService.saveBatch(tblProductEntity.getProductParamEntityList());
        }
        //发送发布消息
        TblMessageEntity messageEntity = new TblMessageEntity();
        messageEntity.setMerchantId(tblProductEntity.getMerchantId());
        messageEntity.setType(0);
        messageEntity.setJoinId(tblProductEntity.getId());
        asyncTask.sendMessage(messageEntity);
        return R.success();
    }

    @Override
    public R delete(Long id) {
        TblProductEntity tblProductEntity = new TblProductEntity();
        tblProductEntity.setId(id);
        baseMapper.updateById(tblProductEntity);
        return R.success(baseMapper.deleteById(id));
    }

    @Override
    public R updateData(TblProductEntity tblProductEntity) {
        //修改商品表信息
        baseMapper.updateById(tblProductEntity);
        //增加轮播图片
        List<TblProductImageEntity> tblProductImageAddList = tblProductEntity.getTblProductImageAddList();
        if (tblProductImageAddList.size()>0){
            tblProductImageAddList.forEach(item ->{
                item.setProductId(tblProductEntity.getId());
                tblProductImageService.add(item);
            });
        }
        //删除轮播图图片
        List<TblProductImageEntity> tblProductImageDeleteList = tblProductEntity.getTblProductImageDeleteList();
        if (tblProductImageDeleteList.size()>0){
            QueryWrapper<TblProductImageEntity> queryWrapper = new QueryWrapper<>();
            tblProductImageDeleteList.forEach(item ->{
                queryWrapper.clear();
                queryWrapper.eq("image_url", item.getImageUrl());
                tblProductImageService.remove(queryWrapper);
                ossUtil.removeFile(item.getImageUrl());
            });
        }

        //增加商品扩展介绍图片
        List<TblProductExtendImageEntity> productIntroduceExtendImagesAdd = tblProductEntity.getProductIntroduceExtendImagesAdd();
        if (productIntroduceExtendImagesAdd.size()>0){
            productIntroduceExtendImagesAdd.forEach(item ->{
                item.setPid(tblProductEntity.getId());
                productExtendImageService.add(item);
            });
        }
        //删除商品扩展介绍图片
        List<TblProductExtendImageEntity> productIntroduceExtendImagesDelete = tblProductEntity.getProductIntroduceExtendImagesDelete();
        if (productIntroduceExtendImagesDelete.size()>0){
            QueryWrapper<TblProductExtendImageEntity> queryWrapper = new QueryWrapper<>();
            productIntroduceExtendImagesDelete.forEach(item ->{
                queryWrapper.clear();
                queryWrapper.eq("product_detail_image", item.getProductDetailImage());
                productExtendImageService.remove(queryWrapper);
                ossUtil.removeFile(item.getProductDetailImage());
            });
        }
        //更新商品规格
        if (!ObjectUtils.isEmpty(tblProductEntity.getProductSkuEntityList())) {
            //先删除商品规格再添加
            QueryWrapper<TblProductSkuEntity> removeQuery = new QueryWrapper<>();
            removeQuery.eq("pid", tblProductEntity.getId());
            productSkuService.remove(removeQuery);
            productSkuService.saveBatch(tblProductEntity.getProductSkuEntityList());
        }
        //更新商品扩展介绍
        productExtendService.updateById(tblProductEntity.getProductIntroduceExtend());
        //设置商品参数
        if (!ObjectUtils.isEmpty(tblProductEntity.getProductParamEntityList())) {
            QueryWrapper<TblProductParamEntity> productParamEntityQueryWrapper = new QueryWrapper<>();
            productParamEntityQueryWrapper.eq("pid", tblProductEntity.getId());
            productParamService.remove(productParamEntityQueryWrapper);
            productParamService.saveBatch(tblProductEntity.getProductParamEntityList());
        }
        //传进来的轮播图排序
        List<TblProductImageEntity> productImageEntityList = tblProductEntity.getTblProductImageEntityList();
        //查询出来的轮播图排序
        QueryWrapper<TblProductImageEntity> imageEntityQueryWrapper = new QueryWrapper<>();
        imageEntityQueryWrapper.eq("product_id", tblProductEntity.getId());
        List<TblProductImageEntity> findProductImageEntityList = tblProductImageService.list(imageEntityQueryWrapper);
        //轮播图排序赋值
        findProductImageEntityList.stream().map(item ->productImageEntityList.stream().filter(c->item.getImageUrl().equals(c.getImageUrl())).findFirst().map(c->{
            item.setSort(c.getSort());
            return item;
        }).orElse(item)).collect(Collectors.toList());
        //修改轮播图排序
        tblProductImageService.saveOrUpdateBatch(findProductImageEntityList);
        //传进来的轮播图排序
        List<TblProductExtendImageEntity> productExtendImageEntities = tblProductEntity.getProductIntroduceExtendImages();
        //查询出来的详情img
        QueryWrapper<TblProductExtendImageEntity> extendImageEntityQueryWrapper = new QueryWrapper<>();
        extendImageEntityQueryWrapper.eq("pid", tblProductEntity.getId());
        List<TblProductExtendImageEntity> findProductExtendImageEntities = productExtendImageService.list(extendImageEntityQueryWrapper);
        //详情图排序赋值
        findProductExtendImageEntities.stream().map(item ->productExtendImageEntities.stream().filter(c->item.getProductDetailImage().equals(c.getProductDetailImage())).findFirst().map(c->{
            item.setSort(c.getSort());
            return item;
        }).orElse(item)).collect(Collectors.toList());
        //修改详情图排序
        productExtendImageService.saveOrUpdateBatch(findProductExtendImageEntities);
        return R.success();
    }

    @Override
    public R findById(Long id, String ipAddress, Long userId, String isSys) {
        TblProductEntity tblProductEntity = tblProductEntity(id, ObjectUtils.isEmpty(ipAddress),isSys);
        if (!ObjectUtils.isEmpty(ipAddress)) {
            //增加浏览数方法
            updateProductBrowse(id, ipAddress);
        }
        return R.success(tblProductEntity);
    }

    @Override
    public TblProductEntity tblProductEntity(Long id, Boolean type, String isSys) {
        QueryWrapper<TblProductEntity> productEntityQueryWrapper = new QueryWrapper<>();
        productEntityQueryWrapper.eq("id", id);
        TblProductEntity tblProductEntity = baseMapper.selectOne(productEntityQueryWrapper);
        //验证商品状态
        if (ObjectUtils.isEmpty(tblProductEntity)) {
            throw new RuntimeException(ResultEnum.PRODUCT_IS_NULL.getMsg());
        }
        if (tblProductEntity.getProductBuyZt() != 0 && !type) {
            throw new RuntimeException(ResultEnum.PRODUCT_IS_NULL.getMsg());
        }
        //最新关联的视频地址
        QueryWrapper<TblPopularizeVideoEntity> videoEntityQueryWrapper = new QueryWrapper<>();
        videoEntityQueryWrapper.select("id as videoId, video").eq("pid", id).orderByDesc("create_time").last("limit 1");
        Map<String, Object> videoEntityMap = popularizeVideoService.getMap(videoEntityQueryWrapper);
        tblProductEntity.setVideoEntity(ObjectUtils.isEmpty(videoEntityMap) ? null : videoEntityMap);
        //插入商品轮播图
        QueryWrapper<TblProductImageEntity> imageEntityQueryWrapper = new QueryWrapper<>();
        imageEntityQueryWrapper.eq("product_id", id).orderByAsc("sort");
        //如果后台请求详情，不做图片压缩处理
        if ("1".equals(isSys)){
            tblProductEntity.setTblProductImageEntityList(tblProductImageService.list(imageEntityQueryWrapper));
        }else {
            tblProductEntity.setTblProductImageEntityList(tblProductImageService.list(imageEntityQueryWrapper).stream().peek(item ->item.setImageUrl(item.getImageUrl()+imageDetails)).collect(Collectors.toList()));
        }
        //商品规格
        QueryWrapper<TblProductSkuEntity> skuEntityQueryWrapper = new QueryWrapper<>();
        skuEntityQueryWrapper.eq("pid", id);
        List<TblProductSkuEntity> skuEntityList = productSkuService.list(skuEntityQueryWrapper);
        tblProductEntity.setProductSkuEntityList(skuEntityList);
        //商品介绍
        QueryWrapper<TblProductExtendEntity> extendEntityQueryWrapper = new QueryWrapper<>();
        extendEntityQueryWrapper.eq("pid", id);
        tblProductEntity.setProductIntroduceExtend(productExtendService.getOne(extendEntityQueryWrapper));
        //商品介绍图片
        QueryWrapper<TblProductExtendImageEntity> extendImageEntityQueryWrapper = new QueryWrapper<>();
        extendImageEntityQueryWrapper.eq("pid", id).orderByAsc("sort");
        //如果后台请求详情，不做图片压缩处理
        if ("1".equals(isSys)){
            tblProductEntity.setProductIntroduceExtendImages(productExtendImageService.list(extendImageEntityQueryWrapper));
        }else {
            tblProductEntity.setProductIntroduceExtendImages(productExtendImageService.list(extendImageEntityQueryWrapper).stream().peek(item ->item.setProductDetailImage(item.getProductDetailImage()+imageDetails)).collect(Collectors.toList()));
        }
        //商品参数
        QueryWrapper<TblProductParamEntity> paramEntityQueryWrapper = new QueryWrapper<>();
        paramEntityQueryWrapper.eq("pid", id);
        List<TblProductParamEntity> paramEntityList = productParamService.list(paramEntityQueryWrapper);
        if (paramEntityList.size()>0){
            tblProductEntity.setProductParamEntityList(paramEntityList);
        }
        if (skuEntityList.size()>0){
            //价格
            BigDecimal minProductScribingPrice = skuEntityList.stream().min(Comparator.comparing(TblProductSkuEntity::getProductScribingPrice)).get().getProductScribingPrice();
            BigDecimal maxProductScribingPrice = skuEntityList.stream().max(Comparator.comparing(TblProductSkuEntity::getProductScribingPrice)).get().getProductScribingPrice();
            tblProductEntity.setCrossedPrice(skuEntityList.size() > 1 ? minProductScribingPrice.toString().concat("-").concat(maxProductScribingPrice.toString()) : minProductScribingPrice.toString());
            BigDecimal minPrice = skuEntityList.stream().min(Comparator.comparing(TblProductSkuEntity::getPrice)).get().getPrice();
            BigDecimal maxPrice = skuEntityList.stream().max(Comparator.comparing(TblProductSkuEntity::getPrice)).get().getPrice();
            tblProductEntity.setProductPrice(skuEntityList.size() > 1 ? minPrice.toString().concat("-").concat(maxPrice.toString()) : minPrice.toString());
        }
        //一级分类名称
        tblProductEntity.setCategoryOneName(tblProductCategoryService.getById(tblProductEntity.getCategoryOneId()).getCategoryName());
        //二级分类名称
        tblProductEntity.setCategoryTwoName(tblProductCategoryService.getById(tblProductEntity.getCategoryTwoId()).getCategoryName());
        //三级分类名称
        tblProductEntity.setCategoryThreeName(tblProductCategoryService.getById(tblProductEntity.getCategoryThreeId()).getCategoryName());
        return tblProductEntity;
    }

    @Override
    public R findListByPageClient(Integer page, Integer pageCount, Long merchantId) {
        QueryWrapper<TblProductEntity> wrapper = new QueryWrapper<>();
        wrapper.select("id, merchant_id as merchantId, product_name as productName, product_browse as productBrowse");
        if(!ObjectUtils.isEmpty(merchantId)) {
            wrapper.eq("merchant_id", merchantId);
        }
        wrapper.eq("product_type", 0).orderByDesc("update_time").eq("product_buy_zt", 0);
        Page<TblProductEntity> productEntityPage = page(new Page<>(page, pageCount), wrapper);
        QueryWrapper<TblProductImageEntity> imageWrapper = new QueryWrapper<>();
        QueryWrapper<TblProductSkuEntity> skuEntityQueryWrapper = new QueryWrapper<>();
        productEntityPage.getRecords().forEach(item -> {
            imageWrapper.clear();
            imageWrapper.eq("product_id", item.getId()).orderByAsc("sort").last("limit 1");
            TblProductImageEntity imageEntity = tblProductImageService.getOne(imageWrapper);
            item.setProductCover(ObjectUtils.isEmpty(imageEntity) ? null : imageEntity.getImageUrl()+imageCompress);
            //商品最低售价
            skuEntityQueryWrapper.clear();
            skuEntityQueryWrapper.select("price").eq("pid", item.getId()).orderByAsc("price").last("limit 1");
            TblProductSkuEntity skuEntity = skuService.getOne(skuEntityQueryWrapper);
            item.setProductPrice(skuEntity.getPrice().toString());
            //商户信息
            if(ObjectUtils.isEmpty(merchantId)) {
                Map<String, Object> merchantMap = tblMerchantService.getMerchantMap(item.getMerchantId());
                item.setMerchantInfo(merchantMap);
            }
        });
        return R.success(ReturnPageData.fillingData(productEntityPage));
    }

    @Override
    public R findHotProduct() {
        return R.success(baseMapper.selectList(new QueryWrapper<TblProductEntity>().eq("product_buy_zt", 0).orderByDesc("product_browse").last("limit 5")));
    }

    @Override
    public R findKeywordList(String search) {
        List<Map<String, Object>> keywordList = tblProductDao.findKeywordList(search);
        return R.success(keywordList);
    }

    @Override
    public TblProductEntity getProductInfo(Long pid) {
        return baseMapper.getProductInfo(pid);
    }

    @Override
    public R findListPageSearch(Integer current, Integer size, String search) {
        IPage<Map<String, Object>> listPageSearch = baseMapper.findListPageSearch((new Page<>(current, size)), search);
        listPageSearch.getRecords().stream().forEach(item ->{
            Map<String, Object> merchantMap = tblMerchantService.getMerchantMap(Long.valueOf(item.get("merchantId").toString()));
            item.put("merchantInfo", merchantMap);
        });
        return R.success(ReturnPageData.fillingData(listPageSearch));
    }

    @Override
    public R findListPageRecommend(Integer current, Integer size) {
        IPage<Map<String, Object>> listPageRecommend = baseMapper.findListPageRecommend((new Page<>(current, size)));
        listPageRecommend.getRecords().stream().forEach(item ->{
            Map<String, Object> merchantMap = tblMerchantService.getMerchantMap(Long.valueOf(item.get("merchantId").toString()));
            item.put("merchantInfo", merchantMap);
        });
        return R.success(ReturnPageData.fillingData(listPageRecommend));
    }

    @Override
    public R specialOfferList() {
        QueryWrapper<TblProductEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("product_type", 1).orderByDesc("update_time").eq("product_buy_zt", 0);
        List<TblProductEntity> productEntityList = list(wrapper);
        QueryWrapper<TblProductImageEntity> imageWrapper = new QueryWrapper<>();
        QueryWrapper<TblProductSkuEntity> skuEntityQueryWrapper = new QueryWrapper<>();
        productEntityList.forEach(item -> {
            imageWrapper.clear();
            imageWrapper.eq("product_id", item.getId()).orderByAsc("sort").last("limit 1");
            TblProductImageEntity imageEntity = tblProductImageService.getOne(imageWrapper);
            item.setProductCover(ObjectUtils.isEmpty(imageEntity) ? null : imageEntity.getImageUrl()+imageCompress);
            //商品售价
            skuEntityQueryWrapper.clear();
            skuEntityQueryWrapper.select("price,id").eq("pid", item.getId()).orderByAsc("price").last("limit 1");
            TblProductSkuEntity skuEntity = skuService.getOne(skuEntityQueryWrapper);
            item.setProductPrice(skuEntity.getPrice().toString());
            item.setSpecialSkuId(skuEntity.getId());
            //商户信息
            Map<String, Object> merchantMap = tblMerchantService.getMerchantMap(item.getMerchantId());
            item.setMerchantInfo(merchantMap);
        });
        return R.success(productEntityList);
    }

    /**
     * 增加浏览数
     *
     * @param id
     * @param ipAddress
     */
    public void updateProductBrowse(Long id, String ipAddress) {
        if (!redisUtil.hasKey("browse:" + id + ipAddress)) {
            //如果不存在，增加浏览量
            TblProductEntity product = new TblProductEntity();
            product.setId(id);
            baseMapper.updateProductBrowse(product);
            redisUtil.set("browse:" + id + ipAddress, "1", 1800L);
        }
    }
}
